package com.lelefly.base.filter;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lelefly.Log.Logger;
import com.lelefly.base.daoimp.BaseDao;
import com.lelefly.constant.Constant;

public class LeleflyBaseIntercept implements HandlerInterceptor, Logger {
	public Long before;

	@Resource
	private BaseDao baseDao;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		// TODO Auto-generated method stub
//		String servlet = request.getRequestURI().substring(
//				request.getRequestURI().lastIndexOf("/") + 1);
		String servlet = request.getRequestURI();
		String device_id= request.getParameter("device_id");
		String version= request.getParameter("version");
		String sLoginUrl = request.getContextPath() + "/distributor/toLogin";
		System.out.println(sLoginUrl);
//		response.sendRedirect(sLoginUrl);
		if (servlet.contains("sys") || servlet.contains("toHome")) {
			Object str = (Object) request.getSession().getAttribute(Constant.SESSION_INFO);
			if (str != null || StringUtils.equals(sLoginUrl, servlet)) {
				return true;
			}
			response.sendRedirect(sLoginUrl);
			return false;
		}
		if (true) {
			getLogger().info("设备id  ["+device_id+"]"+
					"调用  api [" + servlet + "]  在时间  "
							+ sdf.format(new Date()));
		}
		return true;
	}

	@Override
	public org.apache.log4j.Logger getLogger() {
		// TODO Auto-generated method stub
		return org.apache.log4j.Logger.getLogger(LeleflyBaseIntercept.class);
	}

}
